// 创建用户相关的小仓库
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import type { loginFormData } from '@/api/user/type'
import { UserState } from './types/type'
import cloneDeep from 'lodash/cloneDeep'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由(常量路由)
import { constantRoute, asnycRoute, anyRoute } from '@/router/routes'
import router from '@/router'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      menuRoutes: constantRoute,
      token: GET_TOKEN(),
      username: '',
      avatar: '',
      user_id: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
    }
  },
  // 异步逻辑
  actions: {
    // 用户登录
    async userLogin(data) {
      const result = await reqLogin(data)

      if (result.code === 200) {
        this.token = result.data.token
        this.user_id = result.data.id
        SET_TOKEN(result.data.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //获取用户信息方法
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      const result = await reqUserInfo()
      //如果获取用户信息成功，存储一下用户信息
      if (result.code == 200) {
        this.username = result.data.name
        // this.avatar = result.data.avatar
        this.buttons = result.data.btns
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asnycRoute),
          result.data.routes,
        )
        //菜单需要的数据整理完毕
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      //退出登录请求
      const result = await reqLogout()
      if (result.code == 200) {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        ElMessage({
          message: '账号已经退出！',
          type: 'success',
        })
        return 'ok'
      }
      // else {
      //   return Promise.reject(new Error(result.message))
      // }
    },
  },
  getters: {},
})

export default useUserStore
